#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: pluginsystem.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  a simple plugin system for vazaar

import os
import sys
import pkg_resources
import gettext

from vazaarlib.constants import PLUGIN_DIR
from vazaarlib.utils import *

sys.modules['vazaar'] = __import__(__name__)
_ = gettext.gettext
#sys.path.insert(0, PLUGIN_DIR)
log = get_logger("plugins")

ENTRYPOINT = 'vazaar.plugins'

def activate_plugins_by_capability(capability, data=None):
    for plugin in get_plugins_by_capability(capability):
        plugin.do_something(data)


def ckeck_plugin_system():
    #FIXME: the plugins are regenerated every single time you start vazaar
    try:
        for plugin_dir in os.listdir(PLUGIN_DIR):
            try:
                os.chdir("%s/%s" % (PLUGIN_DIR, plugin_dir))
                register_plugin(plugin_dir)
            except Exception, e:
                pass
    except Exception, e:
        print e


def register_plugin(name):
    if os.path.exists("setup.py"):
        try:
            #log.info("setting plugin %s up" % name)
            w = os.popen( "python setup.py develop --install-dir .. -m 2>&1 >/dev/null", "w" )
            w.close()
        except Exception, e:
            pass

def init_plugins():
    ckeck_plugin_system()
    pkg_resources.working_set.add_entry(PLUGIN_DIR)
    pkg_env = pkg_resources.Environment([PLUGIN_DIR])
    plugins = {}
    for dir_name in pkg_env:
        egg = pkg_env[dir_name][0]
        egg.activate()
        modules = []
        for plugin_name in egg.get_entry_map(ENTRYPOINT):
            #log.info("loading plugin: %s" % plugin_name)
            entry_point = egg.get_entry_info(ENTRYPOINT, plugin_name)
            try:
                cls = entry_point.load()
                if not hasattr(cls, 'capabilities'):
                    cls.capabilities = []
                instance = cls()
                for c in cls.capabilities:
                    plugins.setdefault(c, []).append(instance)
            except Exception, e:
                log.debug(e)
    log.info(_("plugin system initializated"))

    return plugins

def get_plugins_by_capability(capability):
    return plugins.get(capability, [])

def get_all_plugins():
    result = set()
    for p in plugins.itervalues():
        for plugin in p:
            result.add(plugin)
    return list(result)

"""
def main():
    for plugin in get_plugins_by_capability('foo_capability'):
        print '%s: %s' % (plugin, plugin.do_something())
"""

plugins = init_plugins()
"""
            # check if the plugin has been set up
            log.info("checking %s/%s" % (PLUGIN_DIR, plugin_name))
            if not os.path.exists("%s/%s.egg-link" % (PLUGIN_DIR, plugin_name)):
                try:
                    log.info("setting plugin %s up" % plugin_name)
                    os.chdir("%s/%s" % (PLUGIN_DIR, dir_name))
                    w = os.popen( "python setup.py develop --install-dir .. -m" )
                    w.close()
                except Exception, e:
                    log.debug(e)
            else:
                log.debug("FIXME")
"""
